var sidebar = {
  viewpoints : null,
  myViewpoints: null,
  resource : null,
  relatedViewpoints: null,
  docHtml: null,
  loaded: false,
  currentUri: null,
  selectedFragment: null,

  init: function(){
    // Load page content to dccHtml variable.
    this.doPageLoad();
    // Load hypertopic information (e.g. entity. viewpoints' list).
    this.doRefreshDocument();
    this.loaded = true;
  },

  getViewpoints: function(){
    var setting = getCurrentSetting();
    var filterMyVP = document.getElementById("filter-actor-btn");
    var filterMyVPr = document.getElementById("filter-actor-related-btn");
    var filterVPr = document.getElementById("filter-viewpoint-related-btn");
    var filterVP = document.getElementById("filter-viewpoint-all-btn");

    if(setting.hypertopic.username == ""){
      filterMyVP.removeAttribute("checked");
      filterVP.setAttribute("checked",true);
      filterMyVP.setAttribute("disabled",true);
      filterMyVPr.setAttribute("disabled",true);
    }
    var viewpointsObject = new Viewpoints();
  	viewpointsObject.uri = setting.hypertopic.url + "viewpoint/";
  	debug("[lasuliSidebar.js::getViewpoints] viewpoints uri:" + viewpointsObject.uri, 1);
  	viewpointsObject = viewpointsObject.httpGet(setting.hypertopic.username,setting.hypertopic.password);
  	if(viewpointsObject != false)
  	  this.viewpoints = viewpointsObject.viewpoints;

  	if(setting.hypertopic.username != ""){
      var actorObject = new Actor();
      actorObject.uri = setting.hypertopic.url + "actor/" + setting.hypertopic.username + "/";
      actorObject.name = setting.hypertopic.username;
      var res = actorObject.httpGet(setting.hypertopic.username, setting.hypertopic.password);
      if(res == false)
        this.myViewpoints = null;
      else
        this.myViewpoints = res.viewpoints;
    }
    var_dump("[lasuliSidebar.js::getViewpoints] this.viewpoints:", this.viewpoints, 4);
  },

  getResource: function(url){
    var currentUri = getCurrentUri();
    if(url != null)
      currentUri = url;

    if(typeof(currentUri) != "string" || currentUri.trim() == "" || (currentUri.substring(0, "about:".length) == "about:"))
      return false;

    var setting = getCurrentSetting();

    var requestUrl = setting.hypertopic.url + "resource/" + encodeURIComponent(currentUri);
    var resource = new Resource();
    resource.uri = requestUrl;
    resource.href = currentUri;
    var resource = resource.httpGet(setting.hypertopic.username, setting.hypertopic.password);
    if(resource == false)
      resource = null;
    this.resource = resource;
    var_dump("[lasuliSidebar.js::getResource] resource:", this.resource, 1);
  },

  doRefreshDocument: function(){
    var currentUri = getCurrentUri();
    this.getViewpoints();
    this.getResource(currentUri);
    this.showEntityMenu();
    this.showViewpoints();
  },

  doPageLoad:function(docHtml){
    var currentUri = getCurrentUri();
    if(typeof(currentUri) != "string" || currentUri == ""
      || (currentUri.substring(0, "about:".length) == "about:")
        || (currentUri.substring(0, "chrome:".length) == "chrome:")
          || (currentUri.substring(0, "wyciwyg:".length) == "wyciwyg:"))
      return;

    debug("[lasuliSidebar.js::doPageLoad] sidebar.currentUri:" + this.currentUri,4);
    debug("[lasuliSidebar.js::doPageLoad] currentUri:" + currentUri,4);
    if(docHtml == null){
      docHtml = mainWindow.getBrowser().contentDocument.documentElement.innerHTML;
      if(docHtml.indexOf(HIGHLIGHT_TAG) > 0)
          return;
    }
    this.docHtml = docHtml;
    debug("[lasuliSidebar.js::doPageLoad] docHtml:" + docHtml.substring(0,docHtml.indexOf("\n")),4);
    debug("[lasuliSidebar.js::doPageLoad] docHtml.length:" + docHtml.length,4);

    // Show all highlighted fragments
    this.showHighLighter(true); // page loaded
  },

  doTabSelected: function(){
    debug("[lasuliSidebar.js::doTabSelected] doTabSelected",4);
    var tabsParent = document.getElementById("LaSuli_Sidebar_Tab");
    var uri = sidebarGui.getSelectedPanelViewpointUri();
    // if the sidebar not loaded yet, do nothing
    if(this.loaded)
      this.showHighLighter(true); //when the tab changed
    var entityListMenu = document.getElementById("entity-open-btn");
    var refreshMenu = document.getElementById("refresh-btn");
    var filterTagMenu = document.getElementById("filter-tag-btn");
    var filterViewpointMenu = document.getElementById("filter-viewpoint-btn");
    var viewpointMenu = document.getElementById("create-viewpoint-btn");
    var topicMenu = document.getElementById("create-topic-btn");
    var entityMenu = document.getElementById("create-entity-btn");
    var resourceMenu = document.getElementById("create-resource-btn");
    var attributeMenu = document.getElementById("create-attribute-btn");
    var tagMenu = document.getElementById("tag-btn");

    if(uri != null && uri != ""){
      entityListMenu.setAttribute("style", "display:none");
      viewpointMenu.setAttribute("style", "display:none");
      resourceMenu.setAttribute("style", "display:none");
      attributeMenu.setAttribute("style", "display:none");
      filterViewpointMenu.setAttribute("style", "display:none");

      tagMenu.setAttribute("style", "");
      topicMenu.setAttribute("style", "");
      entityMenu.setAttribute("style", "");
      filterTagMenu.setAttribute("style", "");

      refreshMenu.setAttribute("oncommand","sidebar.showHighLighter(true);");
    }else{
      entityListMenu.setAttribute("style", "");
      viewpointMenu.setAttribute("style", "");
      resourceMenu.setAttribute("style", "");
      attributeMenu.setAttribute("style", "");
      filterViewpointMenu.setAttribute("style", "");

      tagMenu.setAttribute("style", "display:none");
      topicMenu.setAttribute("style", "display:none");
      entityMenu.setAttribute("style", "display:none");
      filterTagMenu.setAttribute("style", "display:none");

      refreshMenu.setAttribute("oncommand","sidebar.doRefreshDocument(true);");
    }

  },

  doCloseViewpointTabPanel : function(){
    var uri = sidebarGui.getSelectedPanelViewpointUri();
    if(uri == null){
      //var sidebarPage = document.getElementById("viewLaSuliSidebar");
      //sidebarPage.removeAttribute("checked");

      //netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
      //toggleSidebar('viewLaSuliSidebar');
    	debug("[lasuliSidebar.js::doCloseViewpointTabPanel] uri is null",1);
    	return;
    }
    var tabPanelsParent = document.getElementById("LaSuli_Sidebar_TabPanel");
    var tabsParent = document.getElementById("LaSuli_Sidebar_Tab");

    debug("[lasuliSidebar.js::doCloseViewpointTabPanel] remove tab panel:" + uri, 4);
    // remove tab panel
    var items = tabPanelsParent.getElementsByTagName('tabpanel');
    for (var i = 0; i < items.length; i++)
      if(items[i].hasAttribute("href") && items[i].getAttribute("href") == uri){
        if(tabPanelsParent.selectedPanel == items[i]){
          tabsParent.selectedIndex = 0;
        }
        tabPanelsParent.removeChild(items[i]);
      }

    // remove tabs and toolbarbutton
    var items = tabsParent.getElementsByTagName('tab');
    for (var i = 0; i < items.length; i++)
      if(items[i].hasAttribute("href") && items[i].getAttribute("href") == uri){
        tabsParent.removeChild(items[i]);
      }
  },

  doOpenViewpointDialog: function(){
    var retVals = { name : null, href:null};
    openDialog("chrome://lasuli/content/viewpointDialog.xul", "dlg-viewpoint", "modal", retVals);
    if(retVals.href != null){
      //this.viewpoints.push(retVals);
      //var_dump("[lasuliSidebar.js::doOpenViewpointDialog] viewpoints:", this.viewpoints, 4);
      this.getViewpoints();
      this.showViewpoints();
    }
  },

  doEntityClick: function(e){
    var menuitem = e.srcElement || e.target;
    var documentPanelCaption = document.getElementById('documentPanelCaption');
    documentPanelCaption.value = "Entity: " +  menuitem.label;
    //alert(menuitem.label);
    sidebar.showPorps(menuitem.getAttribute("href"));
  },

  doTag: function(){
    var stringBundle = document.getElementById("sbLasuli");
    var currentUri = getCurrentUri();
    if(typeof(currentUri) != "string" || currentUri.trim() == ""
        || (currentUri.substring(0, "about:".length) == "about:")
        || (currentUri.substring(0, "chrome:".length) == "chrome:"))
      return;

    var topicName = prompt(stringBundle.getString("sidebar.info.inputTheTopicName"));
    if(topicName == "") return;
    var setting = getCurrentSetting();
    var viewpointUri = sidebarGui.getSelectedPanelViewpointUri();
    var e = new Entity();
    e.uri = setting.hypertopic.url + "entity/" + encodeURIComponent(currentUri) + "/";

  	var t = new Topic();
    t.name = topicName;
    t.viewpoint.href = viewpointUri;
    var tmpEntity = {};
  	tmpEntity.name = "tag";
  	tmpEntity.href = e.uri;
    t.entities.push(tmpEntity);
  	t.href = t.httpPost(viewpointUri + "topic/", setting.hypertopic.username, setting.hypertopic.password);
    if(t.href == null){
  	  alert(stringBundle.getString("sidebar.error.tagFailed"));
  	  return;
  	}

    // Try to find the entity
  	var res = e.httpGet(setting.hypertopic.username, setting.hypertopic.password);
  	if(!res){
      // Not found, just create it!
  	}else{
  	  // Add the topic to current entity
  	  e = res;
  	  e.uri = setting.hypertopic.url + "entity/" + encodeURIComponent(currentUri) + "/";
  	}
  	var resource = e.findResourceByHref(currentUri);
  	if(resource == null){
  	  var sourceName = "Fragment Source";
  	  var timestamp = new Date().getTime();
  	  if(e.findResourceByName(sourceName) != null)
  	    sourceName += "@" + timestamp;

  	  e.addResource(sourceName,currentUri);
      var URIs = parseUri(currentUri);
      var entityName = (URIs.file == null)?topicName:URIs.file;
  	  e.addAttribute("name", entityName);
  	  res = e.httpPut(setting.hypertopic.username, setting.hypertopic.password);
      if(!res){
        var_dump("[lasuliSidebar.js::doTag]", e,4);
      }
  	}
    // Reload TagCloud
    this.showTags();
  },

  showEntityMenu: function(){
    var stringBundle = document.getElementById("sbLasuli");
    var mpEntityList = document.getElementById('mpEntityList');
    var documentPanelCaption = document.getElementById('documentPanelCaption');
    while (mpEntityList.hasChildNodes()) mpEntityList.removeChild(mpEntityList.firstChild);
    //var_dump("[lasuliSidebar.js::showEntityMenu] this.resource:", this.resource , 4);
    if(this.resource == null){
      documentPanelCaption.value = stringBundle.getString("sidebar.info.noEntity");
      var menu = document.createElement('menuitem');
      menu.setAttribute('label', stringBundle.getString("sidebar.info.noEntity"));
      mpEntityList.appendChild(menu);
      documentPanelCaption.value = stringBundle.getString("sidebar.info.noEntity");
      this.relatedViewpoints = null;
      this.showPorps(null);
      return false;
    }
    var_dump("[lasuliSidebar.js::showEntityMenu] this.resource.entities:", this.resource.entities , 1);
    for (var i = 0; i < this.resource.entities.length; i++)
    {
      var tmpEntity = {};
      tmpEntity.name = this.resource.entities[i].name;
      tmpEntity.href = this.resource.entities[i].href;
      if (tmpEntity.href != "") {
        if(tmpEntity.name == "") tmpEntity.name = stringBundle.getString("sidebar.info.entitynoname");
        var menu = document.createElement('menuitem');
        menu.setAttribute('label', tmpEntity.name);
        menu.setAttribute('type', "radio");
        menu.setAttribute('href', tmpEntity.href);
        //menu.setAttribute('oncommand', "sidebar.doEntityClick(this)");
        debug("[lasuliSidebar.js::showEntityMenu] tmpEntity.href:" + tmpEntity.href , 1);
        mpEntityList.appendChild(menu);
        menu.addEventListener("click", sidebar.doEntityClick, false);
        if(i == 0){
          documentPanelCaption.value = "Entity: " + tmpEntity.name;
          menu.setAttribute('checked', true);
          this.showPorps(tmpEntity.href);
        }
      }
    }

    debug("[lasuliSidebar.js::showEntityMenu] get relatedViewpoint", 1);
    var relatedViewpoints = new Array();
    // Get related viewpoints list
    for (var i = 0; i < this.resource.entities.length; i++)
    {
      var entity = new Entity();
      entity.uri = this.resource.entities[i].href;
      entity = entity.httpGet();
      if(entity == false) continue;

      for( var j = 0; j < entity.topics.length; j++){
        var href = entity.topics[j].href;
        if(href != "")
          href = href.substr(0, href.indexOf("/topic/")+1);
        relatedViewpoints.push(href);
      }
      debug("[lasuliSidebar.js::showEntityMenu] this.resource.entities[i].href" + this.resource.entities[i].href, 1);
    }
    this.relatedViewpoints = relatedViewpoints.unique(true);
  },

  doScroll2Fragment: function() {
    if(this.selectedFragment == null) return;
    var fragment = this.selectedFragment.parseJSON();
  	var elementId = "ht_fragment_" + fragment.startPos + "_" + fragment.endPos;
		var doc = content.document;
		var el = doc.getElementById(elementId);
		var valueT = 0, valueL = 0;
		do {
				valueT += el.offsetTop  || 0;
				valueL += el.offsetLeft || 0;
				el = el.offsetParent;
		} while (el);
		content.scrollTo(valueL, valueT);
  },

  doDeleteFragment: function() {
    if(this.selectedFragment == null) return;
    var fragment = this.selectedFragment.parseJSON();
    jsFragments.deleteFragment(fragment);
    this.showHighLighter(true); //delete a fragment
  },

  doUpdateFragmentColor: function(colorIndex) {
    if(this.selectedFragment == null) return;
    var fragment = this.selectedFragment.parseJSON();
    jsFragments.updateFragmentColor(fragment,colorIndex);
    this.showHighLighter(false); //update fragment color
  },

  showPorps: function(url){
    sidebarGui.clearAttributes();
    sidebarGui.clearResources();
    if(url == null) return false;
    var entity = new Entity();
    entity.uri = url;
    entity = entity.httpGet();
    if(entity == false) return false;
    for(var j=0; j < entity.resources.length; j++)
        sidebarGui.addResource(entity.resources[j].name, entity.resources[j].href);
    for(var j=0; j < entity.attributes.length; j++)
        sidebarGui.addAttribute(entity.attributes[j].name, entity.attributes[j].value);
  },

  showViewpoints: function(){
    var filterMyVP = document.getElementById("filter-actor-btn");
    var filterMyVPr = document.getElementById("filter-actor-related-btn");
    var filterVP = document.getElementById("filter-viewpoint-all-btn");
    var filterVPr = document.getElementById("filter-viewpoint-related-btn");

    sidebarGui.clearViewpoints();

    //var_dump("[lasuliSidebar.js::showViewpoints] my vp:", this.myViewpoints,4);
    //var_dump("[lasuliSidebar.js::showViewpoints] all vp:", this.viewpoints,4);
    //var_dump("[lasuliSidebar.js::showViewpoints] related vp:", this.relatedViewpoints,4);
    //var_dump("[lasuliSidebar.js::showViewpoints] filterVP:", filterVP.selected,4);
    // show all my viewpoints
    if(filterMyVP.getAttribute("checked") && this.myViewpoints != null){
      debug("[lasuliSidebar.js::showViewpoints] show all my viewpoints",4);
      for(var i = 0; i < this.myViewpoints.length; i++)
        sidebarGui.showViewpoints_addViewpoint(this.myViewpoints[i].name, this.myViewpoints[i].href);
    }

    // only show my related viewpoints
    if(filterMyVPr.getAttribute("checked") && this.myViewpoints != null && this.relatedViewpoints != null){
      debug("[lasuliSidebar.js::showViewpoints] show all my related viewpoints",4);
      for(var i = 0; i < this.myViewpoints.length; i++)
        if(this.myViewpoints[i].href in oc(this.relatedViewpoints) )
          sidebarGui.showViewpoints_addViewpoint(this.myViewpoints[i].name, this.myViewpoints[i].href);
    }

    // All related viewpoints
    if(filterVPr.getAttribute("checked") && this.viewpoints != null && this.relatedViewpoints != null){
      debug("[lasuliSidebar.js::showViewpoints] show all related viewpoints",4);
      for(var i = 0; i < this.viewpoints.length; i++)
        if(this.viewpoints[i].href in oc(this.relatedViewpoints) )
          sidebarGui.showViewpoints_addViewpoint(this.viewpoints[i].name, this.viewpoints[i].href);
    }

    // All viewpoints
    if(filterVP.getAttribute("checked") && this.viewpoints != null){
      debug("[lasuliSidebar.js::showViewpoints] show all viewpoints",4);
      for(var i = 0; i < this.viewpoints.length; i++)
          sidebarGui.showViewpoints_addViewpoint(this.viewpoints[i].name, this.viewpoints[i].href);
    }
  },
  /**
   * Load all fragments from hypertopic server
   * and highlighter it.
   *
   * If the viewpoint panel is opened, only display related fragments.
   * otherwise display all fragments.
   */
  showHighLighter: function(updateTagCloud){
    if(this.docHtml == null || this.docHtml == "") return;
    debug("[lasulisidebar.js::showHighLighter]",4);

    var currentUri = getCurrentUri();
    if(typeof(currentUri) != "string" || currentUri == ""
      || (currentUri.substring(0, "about:".length) == "about:")
        || (currentUri.substring(0, "chrome:".length) == "chrome:")
          || (currentUri.substring(0, "wyciwyg:".length) == "wyciwyg:"))
      return;
    debug("[lasulisidebar.js::showHighLighter] currentUri:" + currentUri,4);
    jsFragments.init();
    var fragments = null;
    var uri = sidebarGui.getSelectedPanelViewpointUri();
    if(uri != null && uri != ""){
      fragments = jsFragments.getFragmentsByViewpoint(uri);
      sidebarGui.showFragmentsInViewpoints(fragments);
      if(updateTagCloud){
        this.showTags();
      }
    }else{
      fragments = jsFragments.getFragments();
    }
    debug("[lasuliSidebar.js::showHighLighter] viewpoint uri:" + uri,4);
    var_dump("[lasuliSidebar.js::showHighLighter]",fragments,4);
    jsHighLighter.doFormatHtml(this.docHtml, fragments);
  },

  showTags:function(uri){
    var uri = sidebarGui.getSelectedPanelViewpointUri();
  	sidebarGui.clearTagCloud();
    showTagCloud(uri);
    this.filterTags();
  },

  filterTags: function(uri){
    var filter = document.getElementById("filter-tag-btn");
    var tagLabels = document.getElementsByTagName("a");
    if(filter.hasAttribute("checked")){
      var topics = jsFragments.getRelatedTopics();
      var_dump("[lasuliSidebar.js:showTags]", topics, 4);
      for(var i=0; i < tagLabels.length; i++)
        if(tagLabels[i].hasAttribute("uri")){
          debug("[lasuliSidebar.js:showTags] tag:" + tagLabels[i].getAttribute("uri"), 4);
          if(tagLabels[i].getAttribute("uri") in oc(topics)){

          }
          else
            tagLabels[i].setAttribute("style","display:none;");
        }
    }
    else
      for(var i=0; i < tagLabels.length; i++)
        tagLabels[i].setAttribute("style","");
  },

  bgTags: function(evt){
    var node = evt;
    if(node.hasAttribute("fragment")){
      debug("[lasuliSidebar.js::bgTags] node:" + node.getAttribute("fragment"), 4);
      var fragment = node.getAttribute("fragment").parseJSON();
      var topics = new Array();
      for(var i = 0; i < fragment.topics.length; i++)
        topics.push(fragment.topics[i].href);

      var tagLabels = document.getElementsByTagName("a");
      for(var i=0; i < tagLabels.length; i++)
        if(tagLabels[i].hasAttribute("uri")
             && tagLabels[i].getAttribute("uri") in oc(topics)){
            var bgStyle = tagLabels[i].getAttribute("style");
            bgStyle += "background-color: "+ COLORS[fragment.colorIndex] + ";";
            tagLabels[i].setAttribute("style",bgStyle);
        }
    }
  },

  bgOffTags: function(){
      var tagLabels = document.getElementsByTagName("a");
      for(var i=0; i < tagLabels.length; i++)
        if(tagLabels[i].hasAttribute("uri")){
            var bgStyle = tagLabels[i].getAttribute("style");
            if(bgStyle.indexOf("none") > 0)
              tagLabels[i].setAttribute("style","display:none");
            else
              tagLabels[i].setAttribute("style","");
        }
  }
}

window.addEventListener("load", function(){
  sidebar.init();
}, true);